package me.zhangsanfeng.gpss.common.config;

import me.zhangsanfeng.gpss.common.utils.DataUtil;
import me.zhangsanfeng.gpss.entity.Users;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

@Configuration
public class UserCodeAuditorBean implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        if (ctx == null) {
            return null;
        }
        if (ctx.getAuthentication() == null) {
            //登录注销
            //return Optional.ofNullable("anonymous");
            return null;
        }
        if (ctx.getAuthentication().getPrincipal() == null) {
            return null;
        }

        Object principal = ctx.getAuthentication().getPrincipal();
        if (DataUtil.isNotEmpty(principal)){
            if (principal instanceof String){
                return Optional.ofNullable(principal.toString());
            }
            String username = ((Users) principal).getUsername();
            return Optional.ofNullable(username);
        }else {
            return null;
        }
    }

}
